package com.sheyu.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sheyu.common.constant.CartConstant;
import com.sheyu.common.utils.R;
import com.sheyu.mall.cart.exception.CartExceptionHandler;
import com.sheyu.mall.cart.feign.ProductFeignService;
import com.sheyu.mall.cart.interceptor.CartInterceptor;
import com.sheyu.mall.cart.service.CartService;
import com.sheyu.mall.cart.to.UserInfoTo;
import com.sheyu.mall.cart.vo.CartItemVo;
import com.sheyu.mall.cart.vo.CartVo;
import com.sheyu.mall.cart.vo.SkuInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author sheyu
 * @Desciption:
 * @date 2020/9/1 5:12 下午
 */

@Service
public class CartServiceImpl  implements CartService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public List<CartItemVo> getUserCartItems() {
        List<CartItemVo> cartItemVos = new ArrayList<>();

        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId()==null){
            cartItemVos = null;
        }else{
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            if(cartItems==null){
                throw new CartExceptionHandler();
            }else{
                cartItemVos = cartItems.stream().map(item->{
                    BigDecimal price = productFeignService.getPrice(item.getSkuId());
                    item.setPrice(price);
                    return item;
                }).collect(Collectors.toList());

            }
        }
        return cartItemVos;
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if(userInfoTo.getUserId()!=null){
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            String tmpCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> tmpCartItemVos = getCartItems(tmpCartKey);
            if (tmpCartItemVos!=null){
                for (int i = 0; i < tmpCartItemVos.size(); i++) {
                    //添加商品到购物车或者更新数量
                    addToCart(tmpCartItemVos.get(i).getSkuId(),tmpCartItemVos.get(i).getCount());
                }
                //清理临时购物车
                clearCartSkuInfo(tmpCartKey);
            }
            List<CartItemVo> cartItemVos = getCartItems(cartKey);
            cartVo.setItems(cartItemVos);
            cartVo.setTotalAmount(cartVo.getTotalAmount());
            cartVo.setCountNum(cartVo.getCountNum());
            cartVo.setCountType(cartVo.getCountType());

        }else{
            //用户未登陆
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItemVos = getCartItems(cartKey);
            cartVo.setItems(cartItemVos);
            cartVo.setTotalAmount(cartVo.getTotalAmount());
            cartVo.setCountNum(cartVo.getCountNum());
            cartVo.setCountType(cartVo.getCountType());

        }
        return cartVo;
    }

    private void clearCartSkuInfo(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 根据skuId是否在redis中，若不在，则从数据库读取对应的商品数据及属性并更新购物车，若存在对应的商品，则更新商品的数量
     * @param skuId
     * @param num
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public void addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //获取未登陆或者登陆的购物车信息
        BoundHashOperations<String,Object,Object> operations = getCartOps();
        //根据skuId获取购物车数据
        String resultOfCart = (String) operations.get(skuId.toString());
        if (StringUtils.isBlank(resultOfCart)){
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getProductSkuInfo = CompletableFuture.runAsync(()->{
                R productSkuInfo = productFeignService.getInfo(skuId);
                SkuInfoVo skuInfo = productSkuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            },executor);
            CompletableFuture<Void> getAttrValue = CompletableFuture.runAsync(()->{
                List<String> stringList = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(stringList);
            },executor);
            CompletableFuture.allOf(getAttrValue,getProductSkuInfo).get();

            String cartItemVoString = JSON.toJSONString(cartItemVo);

            operations.put(skuId.toString(),cartItemVoString);
        }else{
            //如果存在，就修改商品的数量
            CartItemVo cartItemVo = JSON.parseObject(resultOfCart,CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            String cartItemVoString = JSON.toJSONString(cartItemVo);
            operations.put(skuId.toString(),cartItemVoString);
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String,Object,Object> operations = getCartOps();
        String resultOfCart = (String) operations.get(""+skuId);
        CartItemVo cartItemVo = JSON.parseObject(resultOfCart,CartItemVo.class);
        return cartItemVo;
    }

    /**
     * 修改购物车商品的数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String,Object,Object> operations = getCartOps();
        //根据skuId获取购物车数据
        String cartItemVoString = (String) operations.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(cartItemVoString,CartItemVo.class);
        cartItemVo.setCount(cartItemVo.getCount()+num);

        String cartItemVoStringOfChange = JSON.toJSONString(cartItemVo);
        operations.put(skuId.toString(),cartItemVoStringOfChange);
    }

    /**
     * 改变购物车商品的数量
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String,Object,Object> operations = getCartOps();
        //根据skuId获取购物车数据
        String cartItemVoString = (String) operations.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(cartItemVoString,CartItemVo.class);
        boolean checkValue = check==1?true:false;
        cartItemVo.setCheck(checkValue);

        String cartItemVoStringOfChange = JSON.toJSONString(cartItemVo);
        operations.put(skuId.toString(),cartItemVoStringOfChange);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String,Object,Object> operations = getCartOps();
        String cartItemVoString = (String) operations.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(cartItemVoString,CartItemVo.class);
        cartItemVo.setCount(num);
        String cartItemVoStringOfChange = JSON.toJSONString(cartItemVo);
        operations.put(skuId.toString(),cartItemVoStringOfChange);
    }

    /**
     * 删除购物车中的商品
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String,Object,Object> operations = getCartOps();
        operations.delete(skuId.toString());
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId()!=null){
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        }else{
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }


    public List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations<String,Object,Object> boundHashCartItems = redisTemplate.boundHashOps(cartKey);
        List<Object> values = boundHashCartItems.values();
        if (values!=null&&values.size()>0){
            List<CartItemVo> cartItemVos = values.stream().map((item)->{
                String cartItemVoForString = (String) item;
                CartItemVo cartItemVo = JSON.parseObject(cartItemVoForString,CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return cartItemVos;
        }
        return null;
    }
}
